/*
 * 
 * Author	 	- Rakesh Kumar Jha
 * Date			- Oct 11, 2010
 * Version		- 5.7
 * Desc			- This activity will handle the validation of password, and based on that redirected to mail box.
 *   	
 */
package com.ssc.olec;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ValidatePassword extends Activity  {
	private Button validate_password_button;
	private Button change_password_button;

	public static boolean isvalidated = false;
	private NotificationManager mNotificationManager;
	private int SIMPLE_NOTFICATION_ID;
	private Notification notifyDetails;

	View viewParam;
	public static String password = "";
	public static String validatepassword = "";
	ProgressDialog myProgressDialog;
	Cursor cursor;

	public static final String USER_PASSWORD_TABLE = "USER_PASSWORD";
	SQLiteDatabase dh ;
	EditText tValidatePassword;
	private String typeOfIntent = null;
	private String sEmailId = null;
	String userName;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/*
		 * myProgressDialog =
		 * ProgressDialog.show(ValidatePassword.this,"Please wait......"
		 * ,"Validating Password", true);
		 * 
		 * new Thread() { public void run() { try{ // Do some Fake-Work
		 * sleep(5000); } catch (Exception e) { } // Dismiss the Dialog
		 * myProgressDialog.dismiss(); } }.start();
		 */


		// To check the Notification Type from the Intent
		Intent intentType = getIntent();
		if (intentType != null) {
			Bundle bundle = intentType.getExtras();
			if (bundle != null) {
				typeOfIntent = bundle.getString("Type");
				sEmailId = bundle.getString("EMailId");
				System.out.println("Type: " + typeOfIntent);
			}
		}
		
		setContentView(R.layout.validate_password);
		
		dh = OLECDatabase.getInstance().getDb();
		
		// etUsername =
		// (CheckUsernameEditText)findViewById(R.id.t_validate_password);

		tValidatePassword = (EditText) findViewById(R.id.t_validate_password);
		validatepassword = tValidatePassword.getText().toString();

		tValidatePassword.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				try {
					if (tValidatePassword.length() == 0	|| tValidatePassword.equals("")) {
						validate_password_button.setEnabled(false);
					}

					if (tValidatePassword.length() >= 1) {
						change_password_button.setEnabled(true);
						validate_password_button.setEnabled(true);
					}
					/*if ((tValidatePassword.getText().toString()	.equals(password))) {
						change_password_button.setEnabled(true);
					} */else {
						change_password_button.setEnabled(false);
					}
				} catch (NumberFormatException e) {
				}
			}
		});

		cursor = dh.query(USER_PASSWORD_TABLE, new String[] { "user_id",
				"user_name", "password" }, null, null, null, null, null);
		startManagingCursor(cursor);

		if (cursor.moveToLast()) {
			userName=cursor.getString(1);
				
		}
		System.out.println("saved password  =" + password);
		
		validate_password_button = (Button) findViewById(R.id.validate_password_button);
		change_password_button = (Button) findViewById(R.id.validate_password_change_button);

	/*	if (PasswordUtil.getSecurityLevel() == PasswordUtil.K_SECURITY_LEVEL_HIGH) {

			tValidatePassword.setInputType(InputType.TYPE_CLASS_TEXT
					| InputType.TYPE_TEXT_VARIATION_PASSWORD);
}*/
		validate_password_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View viewParam) {
				String enteredPass = tValidatePassword.getText().toString();

				if (enteredPass == null || enteredPass.trim().equals(""))

				{

					Toast.makeText(ValidatePassword.this,"Please enter password", 4000).show();

					validate_password_button.setEnabled(false);

				}

				else if (!(enteredPass.equals(password)))

				{

					Toast.makeText(ValidatePassword.this,"Please enter correct password",
							4000).show();

					validate_password_button.setEnabled(false);

					tValidatePassword.setText("");

				}

				else

				{

					Intent myIntent = new Intent(ValidatePassword.this,AdminMainActivity.class);
					startActivity(myIntent);
					finish();
				}
			}
		});
	

		/*
		 * etUsername.setOnUsernameAvailableListener(new
		 * OnUsernameAvailableListener() {
		 * 
		 * 
		 * public void onAvailableChecked(String username, boolean available) {
		 * // Handle the event here if(!available){
		 * change_password_button.setEnabled(true);
		 * 
		 * } else { change_password_button.setEnabled(false); } } });
		 */
		this.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
		

	}

	/*public void onStateChange(int errorCode) {
		// TODO Auto-generated method stub
		// Here dismiss Validating message Progress dialog
		System.out.println("Error code -- " + errorCode);
		if (errorCode == 0) {
		//	System.out.println("Connection Success");
			// This if condition for Success Scenario
			// Redirect UI to SetChangePassword Page // This one u can ignore
			// this one
			// Check whether pwd is saved for User in DB and static variable
			// check in Change Pwd (Enter/Validate Pwd)

			// if(Mailbox_home.settingVariable&&Mailbox_home.settingVariable1)
			// {
			// Intent myIntent = new Intent(SettingsActivity.this,
			// Mailbox_home.class);
			// startActivityForResult(myIntent,
			// Intent.FLAG_ACTIVITY_NO_ANIMATION);
			// }
			// else
			// {
			// Intent myIntent = new Intent(SettingsActivity.this,
			// set_password.class);
			// Bundle userNameSetPassword=new Bundle();
			// userNameSetPassword.putString("userName", userName);
			// myIntent.putExtras(userNameSetPassword);
			// startActivityForResult(myIntent,
			// Intent.FLAG_ACTIVITY_NO_ANIMATION);
			// }

			// ClientConfig oConfig = new ClientConfig();
			// Property oProp = oConfig.getProperty(
			// PropertyID.CONNECTION_USER_NAME, false );

		} else if (errorCode == MoExceptionMessages.COMMERR_TMERR_DEVICEVAL_WRONG_USER
				|| errorCode == MoExceptionMessages.COMMERR_TMERR_DEVICEVAL_WRONG_DEVICE
				|| errorCode == MoExceptionMessages.COMMERR_TMERR_DEVICEVAL_INVALID_VAL_CODE
				|| errorCode == MoExceptionMessages.COMMERR_TMERR_DEVICEVAL_VALCODE_CHK_FAILED) {
			// This condition for error messages which are
			// specific wrong device and other condtions
			// System.out.println("Connection failed");
			// Show the Alert Dialog here
			// ClientApp.getApp().uninitialize();
			// PlatformUtils.stopService(com.sybase.mo.MessagingService.class);
			try {
				boolean validatePasswordErrorPref = SettingsPreferenceUtil.getSettingsPreference(getApplicationContext(),SettingsPreferenceUtil.VALIDATE_PASSWORD_ERROR_PREFS_KEY);

		//		System.out.println("Inbox Mail List : VALIDATE_PASSWORD_ERROR_PREFS_KEY: "+ validatePasswordErrorPref);
				ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
				ArrayList<RunningTaskInfo> runningTaskInfo = (ArrayList<RunningTaskInfo>) am
						.getRunningTasks(1);
				String curActivity = null;
				for (RunningTaskInfo runningTask : runningTaskInfo) {
					curActivity = runningTask.topActivity.getClassName();
				}
		//		System.out.println("Validate Password - Current Activity: "	+ curActivity);
				if (curActivity != null
						&& curActivity.contains("ValidatePassword")) {
					if (validatePasswordErrorPref) {
				//		System.out.println("Show Dialog: ");
						m_oGUIRefreshHandler.post(m_oUpdateUI);
						SettingsPreferenceUtil.putSettingsPreference(getApplicationContext(),SettingsPreferenceUtil.VALIDATE_PASSWORD_ERROR_PREFS_KEY,false);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			// Redirect to Alert Dialog which displays error message
		}

	}

	// Handler used for posting UI events
	final Handler m_oGUIRefreshHandler = new Handler();

	// Create runnable for posting to the handler
	final Runnable m_oUpdateUI = new Runnable() {
		public void run() {
			updateResultsInUI();
		}

	};

	private void updateResultsInUI() {

		try {
			System.out.println("Validate Password Update UI");
			new AlertDialog.Builder(this)


					.setTitle(R.string.string_edit_settings_alert_title)
					.setMessage(R.string.string_edit_settings_alert_message)
					.setPositiveButton(R.string.string_edit_setting_alert_positive_button,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int whichButton) {
									Intent myIntent = new Intent(ValidatePassword.this,SettingsActivity.class);
									startActivity(myIntent);//Intent.FLAG_ACTIVITY_NO_ANIMATION);
								}
							}).show();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}*/

	
}
